package com.whz.work.ex01;

import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName Request
 * @Description TODO 表示一个HTTP请求
 * @Author hong-zhi
 * @Date 2021/5/27 18:27
 * @Version 1.0
 */
@Slf4j
public class Request {
    private InputStream input;
    private String uri;

    public Request(InputStream input) {
        this.input = input;
    }

    /**
     * 从请求信息中解析文件名称URI
     */
    public void parse() {
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try {
            i = input.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            i = -1;
        }
        for (int j = 0; j < i; j++) {
            request.append((char) buffer[j]);
        }
        uri = parseUri(request.toString());
    }

    /**
     * 从请求信息中获取要访问的目标文件名称
     * @param requestString
     * @return
     */
    private String parseUri(String requestString) {
        int index1, index2;
        index1 = requestString.indexOf(' ');
        if (index1 != -1) {
            index2 = requestString.indexOf(' ', index1 + 1);
            if(index2 > index1) {
                uri = requestString.substring(index1 + 1, index2);
            }
        }
        log.info("解析URL得到的文件名称: {}", uri);
        return uri;
    }

    public String getUri() {
        return uri;
    }

    @Override
    public String toString() {
        return "Request{" +
                "uri='" + uri + '\'' +
                '}';
    }
}
